package me.flyray.admin.rest;

import me.flyray.admin.biz.*;
import me.flyray.admin.constant.AdminCommonConstant;
import me.flyray.admin.mapper.UserMapper;
import me.flyray.admin.rpc.service.PermissionService;
import me.flyray.admin.rpc.service.UserRoleService;
import me.flyray.admin.rpc.service.UserService;
import me.flyray.admin.entity.*;
import me.flyray.admin.vo.*;
import me.flyray.auth.common.config.UserAuthConfig;
import me.flyray.common.msg.BaseApiResponse;
import me.flyray.common.msg.ResponseCode;
import me.flyray.common.msg.TableResultResponse;
import me.flyray.common.rest.BaseController;
import me.flyray.common.util.SnowFlake;
import me.flyray.common.util.TreeUtil;
import me.flyray.common.vo.QueryPersonalBaseListRequest;
import me.flyray.common.vo.admin.AdminUserRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ${DESCRIPTION}
 *
 * @author wanghaobin
 * modify by bolei
 * @create 2017-06-08 11:51
 */
@RestController
@RequestMapping("user")
public class UserController extends BaseController<UserBiz, User> {
	
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private MenuBiz menuBiz;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleBiz roleBiz;
    @Autowired
    private DeptBiz deptBiz;
    @Autowired
	private UserAuthConfig userAuthConfig;
    @Autowired
    private BaseAreaBiz areaBiz;
    @Autowired
    private UserMapper userMapper;
    
    
    @RequestMapping(value = "/front/info", method = RequestMethod.GET)
    @ResponseBody
    public BaseApiResponse getUserInfo() throws Exception {
        FrontUser userInfo = permissionService.getUserInfo(request.getHeader(userAuthConfig.getTokenHeader()));
        if(userInfo==null) {
            return BaseApiResponse.newFailure(ResponseCode.USERINFO_NOTEXIST);
        } else {
            return BaseApiResponse.newSuccess(userInfo);
        }
    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @ResponseBody
    public BaseApiResponse getUserAllInfo() throws Exception {
        FrontUser userInfo = permissionService.getUserInfo(request.getHeader(userAuthConfig.getTokenHeader()));
        if(userInfo==null) {
            return BaseApiResponse.newFailure(ResponseCode.USERINFO_NOTEXIST);
        } else {
            return BaseApiResponse.newSuccess(userInfo);
        }
    }

    /**
     * 获取该用户拥有的菜单权限
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/menus", method = RequestMethod.GET)
    @ResponseBody
    public BaseApiResponse getMenusByUsername() throws Exception {
        List<MenuTree> list = permissionService.getMenusByUsername(request.getHeader(userAuthConfig.getTokenHeader()));
        return BaseApiResponse.newSuccess(list);
    }
    
    /**
	 * 新增用户并分配角色
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<?> addUser(@RequestBody UserVo req) throws Exception {
		User entity = new User();
        //商户号crc自校验数据 目的防止伪造造成脏数据
		String userId = String.valueOf(SnowFlake.getId());
		BeanUtils.copyProperties(req, entity);
		entity.setUserId(userId);
		//根据角色获取平台编号
		Role role = roleBiz.selectById(req.getRoleId());
		Dept dept = deptBiz.selectById(role.getDeptId());
		String platformId = dept.getPlatformId();
		entity.setPlatformId(platformId);
		
		//地区
		BaseAreaRequestParam param = new BaseAreaRequestParam();
		param.setAreaCode(req.getAreaCode());
        BaseArea area = areaBiz.QueryAreaInfo(param);
        if (area != null){
            entity.setAreaCode(area.getAreaCode());
            entity.setAreaLayer(String.valueOf(area.getLayer()));
            entity.setAreaName(area.getName());
        }
		if (!StringUtils.isEmpty(req.getParentId())){
            entity.setParentId(req.getParentId());
            User queryUser = new User();
            queryUser.setUserId(req.getParentId());
            queryUser = userMapper.selectOne(queryUser);
            entity.setParentName(queryUser.getUsername());
        }

		userService.addUser(entity);
		UserRole userRole = new UserRole();
		//目前只支持一个用户一个角色
		userRole.setRoleId(req.getRoleId());
		userRole.setUserId(userId);
		userRoleService.addUserRole(userRole);
        return ResponseEntity.ok(entity);
    }

    @RequestMapping(value = "/update/{id}",method = RequestMethod.PUT)
    @ResponseBody
    public BaseApiResponse<User> updateUser(@RequestBody User entity, @PathVariable int id){
        if (!StringUtils.isEmpty(entity.getParentId())){
            entity.setParentId(entity.getParentId());
            User queryUser = new User();
            queryUser.setUserId(entity.getParentId());
            queryUser = userMapper.selectOne(queryUser);
            entity.setParentName(queryUser.getUsername());
        }
        baseBiz.updateSelectiveById(entity);
        return BaseApiResponse.newSuccess(entity);
    }

    @RequestMapping(value = "/pageList",method = RequestMethod.POST)
    @ResponseBody
    public TableResultResponse<User> pageList(@RequestBody AdminUserRequest bean){
    	bean.setPlatformId(setPlatformId(bean.getPlatformId()));
        return baseBiz.pageList(bean);
    }

    /**
     * 组织架构中候选领导列表
     * @param bean
     * @return
     */
    @RequestMapping(value = "/candidateLeaders",method = RequestMethod.POST)
    @ResponseBody
    public BaseApiResponse<List<User>> candidateLeaders(@RequestBody AdminUserRequest bean){
        //查询出上级上级部门
        Dept dept = new Dept();
        dept.setDeptId(bean.getDeptId());
        dept = deptBiz.selectOne(dept);
        User superior = new User();
        superior.setDeptId(dept.getParentId());
        List<User> superiors = baseBiz.selectList(superior);
        User user = new User();
        user.setDeptId(bean.getDeptId());
        List<User> result = new ArrayList<>();
        List<User> users = baseBiz.selectList(user);
        if (users != null){
            superiors.addAll(users);
        }
        return BaseApiResponse.newSuccess(result);
    }

    /**
     * 修改用户密码
     * @author centerroot
     * @time 创建时间:2018年8月27日下午3:08:12
     * @param req
     * @return
     */
    @RequestMapping(value = "/updateUserPwd", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateUserPwd(@RequestBody UserPassword req) {
        req.setPassword(req.getNewPassword());
    	Map<String, Object> resp = baseBiz.updateUserPwd(req);
    	return resp;
    }
    
    /**
     * 重置用户密码
     * @author centerroot
     * @time 创建时间:2018年8月27日下午3:32:09
     * @param req
     * @return
     */
    @RequestMapping(value = "/resetUserPwd", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> resetUserPwd(@RequestBody UserPassword req) {
    	Map<String, Object> resp = baseBiz.resetUserPwd(req);
    	return resp;
    }
    
    
    /**
     * 添加用户手机号
     * @author centerroot
     * @time 创建时间:2018年11月21日上午11:35:36
     * @param req
     * @return
     */
    @RequestMapping(value = "/addUserPhone", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addUserPhone(@RequestBody UserPhone req) {
    	Map<String, Object> resp = baseBiz.addUserPhone(req);
    	return resp;
    }

    /**
     * 修改用户手机号
     * @author centerroot
     * @time 创建时间:2018年11月21日上午11:35:36
     * @param req
     * @return
     */
    @RequestMapping(value = "/resetUserPhone", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> resetUserPhone(@RequestBody UserPhone req) {
    	Map<String, Object> resp = baseBiz.resetUserPhone(req);
    	return resp;
    }

}
